import React, { useRef, useState, useEffect } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined, EllipsisOutlined, UserOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Tag, Space, Menu, Dropdown, Image, Switch, Modal, message, Cascader, Skeleton } from 'antd';
// import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { getGoods, addGoods, updateGoods, switchOnBtn, switchRecommendBtn, getCascaderlist, showGoods } from '@/services/goods'
import ProForm, { ProFormDigit, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-form';
import styles from './index.less'
import AliyunOSSUpload from '@/components/AliyunOSSUpload';
import MyEditor from '@/components/MyEditor';

const Goods = () => {
  const actionRef = useRef();
  const [form] = ProForm.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [options, setOptions] = useState([]);
  const [isEdit, setIsEdit] = useState(true);
  const [goodId, setGoodId] = useState(undefined);
  const [initialValues, setInitialValues] = useState({});

  const columns = [
    {
      title: "商品图",
      dataIndex: "cover_url",
      hideInSearch: true,
      render: (_, record) => (
        <Image
          width={64}
          src={record.cover_url}
          placeholder={
            <Image
              preview={false}
              src={record.cover_url}
              width={200}
            />
          } />
      )
    },
    {
      title: "商品名",
      dataIndex: "title",
    },
    {
      title: "价格",
      dataIndex: "price",
      hideInSearch: true,
    },
    {
      title: "库存",
      dataIndex: "stock",
      hideInSearch: true,
    },
    {
      title: "销量",
      dataIndex: "sales",
      hideInSearch: true,
    },
    {
      title: "是否上架",
      dataIndex: "is_on",
      render: (_, record) => (
        <Switch
          checkedChildren="已上架"
          unCheckedChildren="未上架"
          defaultChecked={record.is_on === 1}
          onChange={() => switchOnBtn(record.id)}
        />
      ),
      valueType: "radioButton",
      valueEnum: {
        1: { text: "已上架" },
        0: { text: "未上架" },
      }
    },
    {
      title: "是否推荐",
      dataIndex: "is_recommend",
      render: (_, record) => (
        <Switch
          checkedChildren="已推荐"
          unCheckedChildren="未推荐"
          defaultChecked={record.is_recommend === 1}
          onChange={() => switchRecommendBtn(record.id)}
        />
      ),
      valueType: "radioButton",
      valueEnum: {
        1: { text: "已推荐" },
        0: { text: "未推荐" },
      }
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      hideInSearch: true,
    },
    {
      title: "操作",
      hideInSearch: true,
      render: (_, record) => (
        <a onClick={() => openEdit(record)}>编辑</a>
      )
    },
  ]

  useEffect(async () => {
    const rescategory = await getCascaderlist();
    // console.log('rescategory: ', rescategory);
    if (!rescategory.status) {
      setOptions(rescategory)
    }
  }, [])

  const getData = async (params: any) => {
    const response = await getGoods(params);
    return {
      data: response.data,
      success: true,
      total: response.meta.pagination.total,
    }
  }

  const isShowModal = (flag: boolean) => {
    setIsModalVisible(flag);
  };

  const handleSubmit = async (values: object) => {
    // console.log('values: ', values, isEdit);
    if (isEdit) {
      await addGoods({ ...values, category_id: values.category_id[1] });
      message.success("添加成功");
    } else {
      values.id = goodId;
      await updateGoods({ ...values, category_id: values.category_id[1] });
      message.success("修改成功");
    }
    actionRef.current.reload();
    isShowModal(false);
  }

  const openEdit = async (obj: any) => {
    isShowModal(true);
    setIsEdit(false);
    setGoodId(undefined);
    const result = await showGoods(obj.id);
    // console.log('result: ', result);
    const { pid, id } = result.category;
    const defaultCategory = pid === 0 ? [id] : [pid, id];
    form.setFieldsValue({ ...result, category_id: defaultCategory });
    setInitialValues(result);
    setGoodId(obj.id);
  }

  const setCoverKey = (filekey: any) => {
    form.setFieldsValue({ cover: filekey });
  }

  const setDetails = (value: any) => {
    form.setFieldsValue({ details: value });
  }

  return (
    <PageContainer className={styles.goods}>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => getData(params)}
        /* editable={{
          type: 'multiple',
        }} */
        /* columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }} */
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="商品列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => { setInitialValues({}); setIsEdit(true); isShowModal(true) }}
          >
            新建
          </Button>,
          /* <Dropdown key="menu" overlay={menu}>
          <Button>
            <EllipsisOutlined />
          </Button>
          </Dropdown>, */
        ]}
      />

      <Modal
        destroyOnClose
        title={isEdit ? "添加商品" : "编辑商品"}
        visible={isModalVisible}
        // onOk={handleOk}
        onCancel={() => isShowModal(false)}
        footer={false}
      >
        {
          !goodId && !isEdit ? <Skeleton active={true} paragraph={{ rows: 6 }} /> : <ProForm
            className="form-content"
            onFinish={(values) => handleSubmit(values)}
            form={form}
            preserve={false}
            submitter={{
              // 配置按钮文本
              searchConfig: {
                submitText: isEdit ? '新增' : '修改',
              },
            }}
          >
            <ProForm.Item
              label="分类"
              name="category_id"
              rules={[{ required: true, message: '分类必填项' }]}
            >
              <Cascader
                options={options}
                placeholder="请选择分类"
                fieldNames={{
                  value: "id",
                  label: "name"
                }}
              />
            </ProForm.Item>
            <ProFormText
              name="title"
              required
              label="商品名"
              placeholder="请输入商品名"
              rules={[
                { required: true, message: '商品名必填项' },
              ]}
            />
            <ProFormText
              name="description"
              required
              label="商品描述"
              placeholder="请输入商品描述"
              rules={[
                { required: true, message: '商品描述必填项' },
              ]}
            />
            <ProFormDigit
              name="price"
              required
              label="价格"
              placeholder="请输入价格"
              min={0}
              max={999999}
              rules={[
                { required: true, message: '价格必填项' },
              ]}
            />
            <ProFormDigit
              name="stock"
              required
              label="库存"
              placeholder="请输入库存"
              min={0}
              max={999999}
              rules={[
                { required: true, message: '库存必填项' },
              ]}
            />

            <ProFormText hidden={true} name="cover" />
            <ProForm.Item
              label="商品主图"
              name="cover"
              rules={[
                { required: true, message: '请上传' },
              ]}
            >
              <div>
                <AliyunOSSUpload
                  accept='image/*'
                  setCoverKey={setCoverKey}
                  showUploadList={true}
                >
                  <Button icon={<UploadOutlined />}>点击上传商品主图</Button>
                </AliyunOSSUpload>
                {
                  !initialValues.cover_url ? '' :
                    <Image width={200} src={initialValues.cover_url} />
                }
              </div>
            </ProForm.Item>

            <ProForm.Item
              label="商品详情"
              name="details"
              rules={[
                { required: true, message: '请输入商品详情' },
              ]}
            >
              <MyEditor setDetails={setDetails} content={initialValues.details}></MyEditor>
            </ProForm.Item>
          </ProForm>
        }
      </Modal>
    </PageContainer>
  )
}

export default Goods